<template>
  <div>
    <Card :_Title="route.query.id?'修改地址':'添加新地址'" :_Size="16"></Card>
    <div>
      <a-form ref="formDataRef" :model="formData" :style="{ width: '600px' }" @submit="handleSubmit">
        <a-form-item field="name" label="收件人" :rules="[REQUIRED, VARCHAR20]">
          <a-input v-model="formData.name" placeholder="请输入收件人姓名"></a-input>
        </a-form-item>
        <a-form-item field="address" label="收件地区" :rules="[REQUIRED]">
          <span>{{ formData.address || '暂无地址' }}</span>
          <a-button @click="openAddress()" size="mini" type="outline" status="danger" class="ml_10">选择</a-button>
        </a-form-item>
        <a-form-item field="detail" label="详细地址" :rules="[REQUIRED]">
          <a-input v-model="formData.detail" placeholder="请输入详细地址"></a-input>
        </a-form-item>
        <a-form-item field="mobile" label="手机号码" :rules="[REQUIRED, MOBILE]">
          <a-input v-model="formData.mobile" placeholder="请输入收件人手机号码" :max-length="11"></a-input>
        </a-form-item>
        <a-form-item field="alias" label="地址别名">
          <a-input v-model="formData.alias" placeholder="请输入地址别名，例如公司"></a-input>
        </a-form-item>
        <a-form-item field="isRead" label="默认地址">
          <a-switch v-model="formData.isDefault" checked-color="#ef4444"></a-switch>
        </a-form-item>
        <a-form-item>
          <a-button html-type="submit" type="primary" status="danger" class="mr_10" :loading="loading">保存收货地址</a-button>
          <a-button @click="router.back()">返回</a-button>
        </a-form-item>
      </a-form>

    </div>
    <MultipleMap ref="multipleMap" @callback="getAddress"></MultipleMap>
  </div>
</template>

<script setup lang="ts">
  import { useRouter, useRoute } from 'vue-router';
  import { ref, onMounted } from 'vue';
  import { REQUIRED, VARCHAR20, MOBILE } from '@/utils/validator';
  import { newMemberAddress, editMemberAddress, getAddrDetail } from "@/api/address";
  import { Message } from '@arco-design/web-vue';

  const router = useRouter();
  const route = useRoute();
  const multipleMap = ref();
  const formDataRef = ref();
  // 添加地址表单
  const formData = ref<any>({
    address: '',
    consigneeAddressIdPath: '',
    lat: '',
    lon: '',
  });
  const loading = ref(false);


  const openAddress = () => {
    console.log('multipleMap', multipleMap.value);
    if (multipleMap.value) {
      multipleMap.value.open();
    }
  };
  // 选择地址回调
  const getAddress = (val: any) => {
    if(val.type === 'select'){
      const paths = val.data.map((item: any) => item.name).join(',');
      const ids = val.data.map((item: any) => item.id).join(',');
      formData.value.address = paths;
      formData.value.consigneeAddressIdPath = ids;
      const coord = val.data[val.data.length - 1].center.split(',');
      formData.value.lat = coord[1];
      formData.value.lon = coord[0];
    }
  };
  // 保存收货地址
  const handleSubmit = async () => {
    const auth = await formDataRef.value?.validate();
    if (!auth) {
      const params = JSON.parse(JSON.stringify(formData.value));
      params.consigneeAddressPath = params.address.replace(/\s/g, ",");
      delete params.address;
      loading.value = true;
      if (route.query.id) {
        editMemberAddress(params).then((res) => {
            if (res.data.success) {
              loading.value = false;
              Message.success('修改成功！');
              router.push("/user/home/orderCenter/myAddress");
            }
        }).catch(() => {
          loading.value = false;
        });
      } else {
        newMemberAddress(params).then((res) => {
            if (res.data.success) {
              loading.value = false;
              Message.success('新增成功！');
              router.push("/user/home/orderCenter/myAddress");
            }
        }).catch(() => {
          loading.value = false;
        });
      }
    }
  }

  const getAddrById = (id: any) => {
    // 获取地址详情
    getAddrDetail(id).then((res) => {
      if (res.data.success) {
        const data = res.data.result;
        data.address = res.data.result.consigneeAddressPath.replace(/,/g, " ");
        formData.value = data;
      }
    });
  };

  onMounted(() => {
    if (route.query.id) {
      getAddrById(route.query.id);
    }
  })
</script>

<style scoped lang="less">

</style>
